define(['jquery', 'maybe', 'lodash', 'app/utils'], ($, M, _, U) => {
  'use strict';

  (async function start() {
    M.map(render_foods, await get_foods())
    M.map(render_orders, await get_orders())
    bind_add_food()
  }())

  //bind_add_food : ()
  function bind_add_food() {
    $('#btn-add-food').on('click', add_food)
  }

  //add_food : ()
  function add_food() {
    const name = $('input[name="name"]').val()
    const desc = $('input[name="desc"]').val()
    const price = $('input[name="price"]').val()

    $.post({
      url: '/shop-end/foods',
      data: { name, desc, price }
    }).then(res => {
      if (U.is_res_ok(res)) {
        window.location.reload()
      } else {
        alert('添加菜品失败: ' + U.error(res))
      }
    })
  }

  //get_foods : () -> Maybe (List Food)
  function get_foods() {
    return new Promise((resolve, reject) => {
      $.get('/shop-end/foods')
        .then(res => {
          if (U.is_res_ok(res)) {
            resolve(M.just(U.result(res)))
          } else {
            alert('获取菜品列表失败: ' + U.error(res))
            resolve(M.nothing())
          }
        }, err => {
          alert('服务器响应错误')
          resolve(M.nothing())
        })
    })
  }

  //render_foods : List Food -> ()
  function render_foods(foods) {
    _.map(foods, food => {
      // $('#food_list').append(`<li>${food.name}<small>${food.desc}</small> <button>删除</button></li>`)
      $('#food_list').append(`<a class="collection-item" href="#!"><span class="badge">删除</span> ${food.name}<small>${food.desc}</small> </a>`)
    })
  }

  //get_orders : () -> Maybe (List Order)
  function get_orders() {
    return new Promise((resolve, reject) => {
      $.get('/shop-end/orders')
        .then(res => {
          if(U.is_res_ok(res)){
            resolve(M.just(U.result(res)))
          }else{
            alert('获取订单列表出错: ' + U.error(res))
            resolve(M.nothing())
          }
        }, err => {
          alert('服务器响应错误')
          resolve(M.nothing())
        })
    })



  }

  //render_orders : List Order -> ()
  function render_orders(orders) {
    _.map(orders, o => {
      // $('#order_list').append(`<li>菜名: ${o.food_name} 用户: ${o.user_name} 下单时间: ${o.time} 状态: ${U.order_status(o)} </li>`)

      $('#order_list').append(`<a class="collection-item" href="#!">菜名: ${o.food_name} 用户: ${o.user_name} 下单时间: ${o.time} 状态: ${U.order_status(o)} </a>`)
    })
  }

});